package com.news.servlet.admin;

import com.news.model.Sort;
import com.news.service.NewsService;
import com.news.service.impl.NewsServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/admin/categoryManage")
public class CategoryManageServlet extends HttpServlet {
    private NewsService newsService = new NewsServiceImpl();
    private static final int PAGE_SIZE = 10;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            // 获取当前页码
            int currentPage = 1;
            String pageStr = request.getParameter("page");
            if (pageStr != null && !pageStr.isEmpty()) {
                currentPage = Integer.parseInt(pageStr);
            }

            // 获取搜索关键词
            String keyword = request.getParameter("keyword");
            
            // 获取分类列表和总数
            List<Sort> categoryList;
            int totalCategories;
            
            if (keyword != null && !keyword.trim().isEmpty()) {
                // 执行搜索
                categoryList = newsService.searchSortsByPage(keyword, currentPage, PAGE_SIZE);
                totalCategories = newsService.getTotalSearchSortCount(keyword);
            } else {
                // 获取所有分类
                categoryList = newsService.getSortsByPage(currentPage, PAGE_SIZE);
                totalCategories = newsService.getTotalSortCount();
                
                // 为每个分类获取新闻数量
                for (Sort category : categoryList) {
                    int newsCount = newsService.getNewsBySortId(category.getSort_id());
                    category.setNewsCount(newsCount);
                }
            }
            
            // 计算总页数
            int totalPages = (totalCategories + PAGE_SIZE - 1) / PAGE_SIZE;
            
            // 设置属性
            request.setAttribute("categoryList", categoryList);
            request.setAttribute("currentPage", currentPage);
            request.setAttribute("totalPages", totalPages);
            request.setAttribute("keyword", keyword);
            
            // 转发到分类管理页面
            request.getRequestDispatcher("/admin/category_manage.jsp").forward(request, response);
            
        } catch (Exception e) {
            request.getSession().setAttribute("message", "获取分类列表失败：" + e.getMessage());
            request.getRequestDispatcher("/admin/category_manage.jsp").forward(request, response);
        }
    }
} 